"""
爬取b站视频


1.获取B站视频网页源代码
2，解析数据，提取我们想要的标题/cid/session
3.把cid session 传入我们找到的playurl这个数据包里面
4.获取json字典数据
5.解析数据提供，音频url 视频url
6.保存数据
7.合成视频 把音频和视频内容合并在一起


三种查询方式，1.通过开发者工具media去查询，
            2.看数据包，搜索mp4,m4s,m4a ,m3u8
            3.一个个去查询，查看相应是否为乱码（二进制形式）
"""
import json
import os.path
import pprint
import re

import requests


def Splicing(title):
    os.system(f'ffmpeg -i "video/{title}.mp4" -i "video/{title}.mp3" -c -y copy "video/{title}.mp4"')
    os.remove(f'video/{title}.mp4')
    os.remove(f'video/{title}.mp3')


def downloads_mp4(title, url, headers):
    res = requests.get(url, headers=headers)
    if not os.path.exists('video'):
        os.mkdir('video')
    with open(f'video/{title}.mp4', 'wb') as f:
        f.write(res.content)


def downloads_mp3(title, url, headers):
    res = requests.get(url, headers=headers)
    if not os.path.exists('video'):
        os.mkdir('video')
    with open(f'video/{title}.mp3', 'wb') as f:
        f.write(res.content)


url = "https://www.bilibili.com/video/BV1ZT4y1d7JM/"
headers = {
    # referer 防盗链
    "Referer": "https://www.bilibili.com/video/BV1bu4y1i7Fc/?spm_id_from=333.788.playrecommendByOp.0&vd_source=91b755576908cc1128487aa65ab08820",
    "Cookie": "buvid3=B884A5B9-F9BC-1C62-3913-7097D067F15642970infoc; b_nut=1691250842; i-wanna-go-back=-1; _uuid=8A9365101-E8EF-B78B-32EE-7FE3A7108B26E51869infoc; buvid4=0CDC58EB-EF42-3452-E841-5D15CA4EA28444642-023080523-qS1NKbptMAuZqs3EsIfEVA%3D%3D; home_feed_column=4; header_theme_version=CLOSE; CURRENT_FNVAL=4048; rpdid=|(J|~u)|~YRk0J'uYmuJ)u)lJ; buvid_fp_plain=undefined; DedeUserID=353877534; DedeUserID__ckMd5=3f337514e9c8e6a5; CURRENT_QUALITY=80; PVID=1; b_ut=5; FEED_LIVE_VERSION=V8; nostalgia_conf=-1; hit-new-style-dyn=1; hit-dyn-v2=1; fingerprint=d9ee51905b59d2f1bccb48db1ef71db8; buvid_fp=d9ee51905b59d2f1bccb48db1ef71db8; bili_ticket=eyJhbGciOiJFUzM4NCIsImtpZCI6ImVjMDIiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE2OTMxMDg4MjEsImlhdCI6MTY5Mjg0OTYyMSwicGx0IjotMX0.dF__7l_SC-O5EevgBQMYfYHQAAy8SUWD7f_Y1NVEWX2RIET1mCjqNuTgUPIZbOJch9p2GjQoKVo_rUP9-X8x-acTYAfOSnYYeEsoHWBlgrMkclhlcSpAQRzmEk1Emwcs; bili_ticket_expires=1693108821; SESSDATA=55922439%2C1708404602%2C035b4%2A81FVsheJqjFBpXyMp2q5HKFgPLTdEkFDclv8TanaHmgQelQ6qg14NnKbx8RFNQbQZpVjfCNwAAIgA; bili_jct=0bb9c2016ae9696aaaf386d8559a610b; sid=6abw7shx; b_lsid=725AED9C_18A34A8AFCA; browser_resolution=1353-675; bp_video_offset_353877534=834319774034952196",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.54"

}

# <h1 title="【2022最新】20个Python爬虫项目实战_一周练完，练完即就业！简历必备项目（附源码）" class="video-title" data-v-4f1c0915=""></h1>
mp4_res = requests.get(url, headers=headers)
print(mp4_res.status_code)

title = re.findall(pattern='<h1 title="(.*?)" class="video-title" data-v-4f1c0915>', string=mp4_res.text)
print(title)
play_info = re.findall(pattern='<script>window.__playinfo__=(.*?)</script>', string=mp4_res.text)[0]
play_info = json.loads(play_info)
print(play_info)
video_url = play_info['data']['dash']['video'][0]['base_url']
audio_url = play_info['data']['dash']['audio'][0]['base_url']
print(video_url)
print('xx')
print(audio_url)
downloads_mp4(title, video_url, headers=headers)
downloads_mp3(title, audio_url, headers=headers)
Splicing(title)
